

// 创建div, className是其类名
function creatediv(className) {
    var div = document.createElement('div');
    div.className = className;
    return div;
}


var d = new Date();
var aTime;


var startTime = d.getTime();
var lastTime = d.getTime();

var arr = [];

function bpm() {
    startTime = lastTime;
    lastTime = new Date().getTime();
    var dTime = lastTime - startTime;
    arr.push(dTime);
    remove();
    getAvg();
}

function remove() {
    if (arr.length > 3) {
        arr.remove(arr[0]);
    }
}


function getAvg() {
    var total = 0;
    for (var i = 0; i < arr.length; i++) {
        total += arr[i];
    }
    //document.getElementById("dTime").innerText = total / arr.length;
    document.getElementById("bpm").innerText = 60000 / (total / arr.length);
    aTime = total / arr.length / 1000;

}

document.getElementById("testbpm").onclick = function (ev) {
    bpm();
};

Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};



var clock = null;
var state = 0;
var speed = 100;
var flag = false;

//点击开始游戏按钮 开始游戏
function reStart() {
    var con = document.getElementById('con');
    con.innerHTML = '';
    document.getElementById('score').innerHTML = 0;
    con.style.top = '-408px';
    clearInterval(clock);
    window.setTimeout('init()', 3000);
}


var b = 4;
var p = 1;
var time;

function init() {
    time = (aTime * 1000.0) / 3;
    console.log(aTime + " -- " + time);
    flag = true;
    for (var i = 0; i < (b * p); i++) {
        createrow();
    }

    document.getElementById('startTime').onkeydown = function (ev) {
        ev = ev || event;
        judge(ev);
    };

    // 定时器
    clock = window.setInterval('move()', time);
}

//qwop 81 87 79 80
var aKey = 81;
var bKey = 87;
var cKey = 79;
var dKey = 80;

// 判断
function judge(ev) {
    var code = ev.keyCode;
    if (code === aKey || code === bKey || code === cKey || code === dKey) {
        var rows = con.childNodes;
        if (rows.length === 9 || rows.length === 8 || rows.length === 7) {
            //console.log("长度：" + rows.length);
            var score = 300;
            var allText = rows[rows.length - 1].innerHTML;
            var bi = allText.indexOf('black');
            var oi = allText.indexOf('orange');

            // 17 南←
            // 41 南→
            // 65 北←
            // 89 北→
            if(code === aKey && bi === 17){
                successJudge(rows[rows.length - 1],score)
            }

            if(code === bKey && oi === 41){
                successJudge(rows[rows.length - 1],score)
            }

            if(code === cKey && oi === 65){
                successJudge(rows[rows.length - 1],score)
            }

            if(code === dKey && bi === 89){
                successJudge(rows[rows.length - 1],score)
            }
        }
    }

}

function successJudge(obj,s) {
    obj.pass = 1;
    score(s);
}

// 判断是否超过音符点，则miss
function over() {
    var rows = con.childNodes;
    if (rows.length === (b * p) + 5 && rows[rows.length - 1].pass !== 1) {
        for (let i = 0; i < rows.length; i++) {
            if (i === (b * p) + 4) {
                var allText = rows[i].innerHTML;
                if (allText.indexOf('black') === -1 && allText.indexOf('orange') === -1) {
                    return;
                }
            }
        }
        fail();
    }
}

// miss
function fail() {
    clearInterval(clock);
    console.log("miss");
    clock = window.setInterval('move()', time);
    //flag = false;
    //confirm('你的最终得分为 ' + parseInt(document.getElementById('score').innerHTML));
}

// 创造一个<div class="row">并且有四个子节点<div class="cell">
function createrow() {
    var con = document.getElementById('con');
    var row = creatediv('row'); //创建div className=row
    var arr = creatcell(); //定义div cell的类名,其中一个为cell black

    con.appendChild(row); // 添加row为con的子节点

    for (var i = 0; i < (b * p); i++) {
        row.appendChild(creatediv(arr[i])); //添加row的子节点 cell
    }

    if (con.firstChild == null) {
        con.appendChild(row);
    } else {
        con.insertBefore(row, con.firstChild);
    }

    runTime();
}

function runTime() {
    var p = document.getElementsByClassName("row");
    for (var i = 0; i < p.length; i++) {
        p[i].style.animationDuration = (aTime * 1000.0) / 3000 + 's';
    }

}

var r = -1;
var count = 0;
// 创建一个类名的数组，其中一个为cell black, 其余为cell
function creatcell() {
    var temp = ['cell', 'cell', 'cell', 'cell'];
    if (r === -1) {
        var i = Math.floor(Math.random() * 4);
        r = i;
        if (r === 0 || r === 3) {
            temp[i] = 'cell black';
        } else {
            temp[i] = 'cell orange';
        }
    } else {
        var j = (Math.random() > 0.5) ? 1 : 0;
        if (j === 0) {
            r -= 1;
        } else {
            r += 1;
        }
        if (r === 4) {
            r -= 2;
        }
        if (r === 0 || r === 3) {
            temp[r] = 'cell black';
        } else {
            temp[r] = 'cell orange';
        }
    }
    if(count < 4){
        temp[0] = 'cell';
        temp[1] = 'cell';
        temp[2] = 'cell';
        temp[3] = 'cell';
    }
    count++;
    return temp;
}

//让方块动起来
function move() {
    var con = document.getElementById('con');
    var top = parseInt(window.getComputedStyle(con, null)['top']);

    if (speed + top > 0) {
        top = 0;
    } else {
        top += speed;
    }
    con.style.top = top + 'px'; //不断移动top值，使它动起来
    over();
    if (top === 0 || top === -8) {
        createrow();
        con.style.top = '-100px';
        delrow();
    }
}


//删除某行
function delrow() {
    var con = document.getElementById('con');
    if (con.childNodes.length === (b * p) + 6) {
        con.removeChild(con.lastChild);
    }
}

// 记分
function score(s) {
    console.log(s);
    var newscore = parseInt(document.getElementById('score').innerHTML) + s; //分数加一
    document.getElementById('score').innerHTML = newscore; //修改分数
}
